package com.tsinghuabigdata.edu.ddmath.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.view.CircleImageView;

import roboguice.activity.RoboActionBarActivity;

/**
 * <p>
 * Created by yanshen@tsinghuabigdata.com on 2015/10/28.
 * </p>
 * <p/>
 * 带ActionBar的RoboActivity
 *
 * @author yanshen@tsinghuabigdata.com
 * @version V1.0
 * @packageName: com.tsinghuabigdata.edu.ddmath.activity
 * @createTime: 2015/10/28 11:08
 */
public class RoboForActionBarActivity extends RoboActionBarActivity {

    public static final String ACTION = "FINISH_ALL";

    private TextView leftBtn;
    private TextView bar_second_left_btn;
    private TextView title;
    private ImageView left_icon;
    private CircleImageView left_img;
    private ImageView rightIcon;
    private ImageView rightIcon2;
    private TextView barRightBtn;
    private RelativeLayout relBarMask;
    private FinishReceiver mFinishReceiver;
    private SystemBarTintManager tintManager;

    private boolean userBarBackgroud = true;

    /**
     * 用户自定义状态栏背景
     *
     * @param use true: 使用activity布局作为背景  false：使用主题色作为背景
     */
    public void setUserBarBackgroud(boolean use) {
        this.userBarBackgroud = use;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Custom_AppCompat);
        super.onCreate(savedInstanceState);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setCustomView(R.layout.action_bar_layout);

        if (userBarBackgroud) {
            getSupportActionBar().getCustomView().setBackgroundResource(R.color.bar_tint);
        }

        leftBtn = (TextView) actionBar.getCustomView().findViewById(R.id.bar_left_btn);
        title = (TextView) actionBar.getCustomView().findViewById(R.id.bar_title);
        left_icon = (ImageView) actionBar.getCustomView().findViewById(R.id.left_icon);
        rightIcon = (ImageView) actionBar.getCustomView().findViewById(R.id.right_icon);
        rightIcon2 = (ImageView) actionBar.getCustomView().findViewById(R.id.right_icon2);

        barRightBtn = (TextView) actionBar.getCustomView().findViewById(R.id.bar_right_btn);
        bar_second_left_btn = (TextView) actionBar.getCustomView().findViewById(R.id
                .bar_second_left_btn);
        left_img = (CircleImageView) actionBar.getCustomView().findViewById(R.id
                .left_img);
        relBarMask = (RelativeLayout) actionBar.getCustomView().findViewById(R.id.rel_mask_container);

        View.OnClickListener leftListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLeftClick();
            }
        };
        leftBtn.setOnClickListener(leftListener);
        left_icon.setOnClickListener(leftListener);

        View.OnClickListener rightListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRightClick();
            }
        };
        rightIcon.setOnClickListener(rightListener);
        rightIcon2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRightClick2();
            }
        });

        View.OnClickListener rightTitleListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRightTitleClick();
            }
        };
        barRightBtn.setOnClickListener(rightTitleListener);

        View.OnClickListener secondLeftListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSecondLeftClick();
            }
        };
        bar_second_left_btn.setOnClickListener(secondLeftListener);

        View.OnClickListener leftImageListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onLeftIconClick();
            }
        };
        left_img.setOnClickListener(leftImageListener);

        initSystemBar(this);
        mFinishReceiver = new FinishReceiver();
        startMonitoring();

    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);

        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setNavigationBarColor(Color.TRANSPARENT);
            getWindow().setStatusBarColor(Color.TRANSPARENT);

            if (hideTitle){
                ActionBar actionBar = getSupportActionBar();
                actionBar.hide();
            }

        } else*/
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            // 兼容4.4或以上的系统
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            // 底部虚拟按键高度
//            if(getSupportActionBar()!=null && OSUtils.isMeiZuBrand()) {
//                View view = ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0);
//                if ( view.getFitsSystemWindows() &&  getSupportActionBar().isShowing()) {
//                    int top = WindowUtils.getActionBarHeight(this) + WindowUtils.getStatusHeight(this);
//                    view.setFitsSystemWindows(false);
//                    ((FrameLayout.LayoutParams) view.getLayoutParams()).setMargins(0, top, 0, 0);
//                    view.requestLayout();
//                }
//            }
        }

    }

    protected void startMonitoring() {
        IntentFilter intentFilter = new IntentFilter(ACTION);
        registerReceiver(mFinishReceiver, intentFilter);
    }

    protected void stopMonitoring() {
        unregisterReceiver(mFinishReceiver);
    }

    /**
     * 关闭所有的Activity
     */
    public void finishAll() {
        sendBroadcast(new Intent(ACTION));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMonitoring();
    }

    public void onLeftClick() {
        //not implemented
        //subclass implemented
    }

    public void onRightClick() {
        //not implemented
        //subclass implemented
    }

    public void onRightClick2() {

    }

    public void onRightTitleClick() {
        //not implemented
        //subclass implemented
    }

    public void onSecondLeftClick() {
        //not implemented
        //subclass implemented
    }

    public void onLeftIconClick() {
        //not implemented
        //subclass implemented
    }


    public void setRightIcon(Drawable drawable) {
        rightIcon.setImageDrawable(drawable);
    }

    public void setRightIcon(int resId) {
        rightIcon.setImageResource(resId);
    }

    public void setRightIcon2(Drawable drawable) {
        rightIcon2.setImageDrawable(drawable);
        barRightBtn.setVisibility(View.GONE);
        rightIcon2.setVisibility(View.VISIBLE);
    }

    public void setRightIcon2(int resId) {
        rightIcon2.setImageResource(resId);
        barRightBtn.setVisibility(View.GONE);
        rightIcon2.setVisibility(View.VISIBLE);
    }

    public void setRightTitle(CharSequence title) {
        rightIcon2.setVisibility(View.GONE);
        barRightBtn.setText(title);
        if (title != null) {
            barRightBtn.setVisibility(View.VISIBLE);
        } else {
            barRightBtn.setVisibility(View.GONE);
        }
    }

    public void setRightTitle(CharSequence title, int color) {
        setRightTitle(title);
        barRightBtn.setTextColor(color);
    }

    public String gettRightTitle() {
        return (String) barRightBtn.getText();
    }

    public TextView getRightBtn() {
        return barRightBtn;
    }

    public void setLeftTitle(CharSequence title) {
        this.leftBtn.setText(title);
        if (TextUtils.isEmpty(title)) {
            left_icon.setVisibility(View.INVISIBLE);
        } else {
            left_icon.setVisibility(View.VISIBLE);
        }
    }
    public void setLeftTitle(CharSequence title, int rId){
        this.leftBtn.setTextColor( getResources().getColor( rId ) );
        setLeftTitle( title );
    }

    public void setLeftIconShow(boolean show) {
        if (show) {
            left_icon.setVisibility(View.VISIBLE);
        } else {
            left_icon.setVisibility(View.INVISIBLE);
        }
    }

    public CharSequence getLeftTitle() {
        return leftBtn.getText();
    }

    public void setSecondLeftTile(CharSequence title) {
        this.bar_second_left_btn.setText(title);
        if (title != null) {
            bar_second_left_btn.setVisibility(View.VISIBLE);
        } else {
            bar_second_left_btn.setVisibility(View.GONE);
        }
    }

    public void setLeftCircleImg(int resId, boolean circle) {
        left_img.setImageResource(resId);
        left_img.setVisibility(View.VISIBLE);
        if (!circle) {
            // 不使用圆角样式
            left_img.setUseDefaultStyle(true);
            left_img.invalidate();
        }
    }

    public void setLeftIcn(int resId) {
        left_icon.setImageResource(resId);
        left_icon.setVisibility(View.VISIBLE);
    }

    public CircleImageView getLeftIcon() {
        return left_img;
    }

    @Override
    public void setTitle(CharSequence title) {
        this.title.setText(title);
    }

    @Override
    public void setTitle(int titleId) {
        this.setTitle(getText(titleId));
    }

    private void initSystemBar(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(activity, true);

            tintManager = new SystemBarTintManager(activity);

            tintManager.setStatusBarTintEnabled(true);
            // 使用颜色资源
            if (userBarBackgroud) {
                tintManager.setStatusBarTintResource(R.color.bar_tint);
            } else {
                tintManager.setStatusBarTintResource(R.color.statubar_bg);
            }

        }

    }


    public void goActivity(Class clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void goActivity(Class clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }

    @TargetApi(19)
    private void setTranslucentStatus(Activity activity, boolean on) {
        Window win = activity.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public void setBarTextcolor(int textcolorid) {
        title.setTextColor(getResources().getColor(textcolorid));
        leftBtn.setTextColor(getResources().getColor(textcolorid));
        bar_second_left_btn.setTextColor(getResources().getColor(textcolorid));
        barRightBtn.setTextColor(getResources().getColor(textcolorid));
    }

    /**
     * 退出监听
     */
    class FinishReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 监听退出消息
            if (intent.getAction() == ACTION) {
                finish();
            }
        }
    }

    /**
     * actionbar罩层
     */
    public void showBarMask() {
        relBarMask.setVisibility(View.VISIBLE);
    }

    public void hideBarMask() {
        relBarMask.setVisibility(View.GONE);
    }

    public void setBarMaskBg(int color) {
        relBarMask.setBackgroundColor(color);
    }

    /**
     * 设置actionbar背景
     */
    public void setActionbarBg(int colorid) {
        getSupportActionBar().getCustomView().setBackgroundResource(colorid);
    }

    public void setActionbarBg(Drawable drawable) {
        getSupportActionBar().getCustomView().setBackground(drawable);
    }

    public void setStatusbarBg(int colorid) {
        if (tintManager != null) {
            tintManager.setStatusBarTintResource(colorid);
        }
    }
}
